
from django_redis import get_redis_connection
from rest_framework import  serializers



class SmsCodeSerializer(serializers.Serializer):
    Text = serializers.CharField(min_length= 4,max_length=4,label="图片验证码")
    image_code_id = serializers.UUIDField(label="验证码编号")

    def validate(self, attrs):
        #1.获取text_code_id
        text = attrs["text"]
        image_code_id = attrs["image_code_id"]

        #2, 取出redis中的验证码
        redis_conn  = get_redis_connection("code")
        redis_text  = redis_conn.get("image_code_%s"%image_code_id)
        print(image_code_id)
        #3.判断是否过期
        if not redis_text:
            raise serializers.ValidationError("验证码已过期")
        #4.删除验证码
        redis_conn.delete("image_code_%s"%image_code_id)
        #5.判断正确性
        if text.upper() != redis_text.decode():
            raise  serializers.ValidationError("验证码错误")
        #6.返回响应
        return attrs



